package com.car.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.car.entity.Car;
import com.car.entity.CarCustom;
import com.car.entity.CarSeach;
import com.car.entity.Support;
import com.car.service.CarManagerService;
import com.car.service.SupportManagerService;


@Controller
@RequestMapping("carManager")
public class CarManagerController {
	
	@Autowired
	@Qualifier("carService")
	private CarManagerService carManager;
	@Autowired
	@Qualifier("supportService")
	private SupportManagerService supportManager;
	
	@RequestMapping(value="/Carstatistical",method={RequestMethod.GET,RequestMethod.POST})
	public String Carstatistical(){
		return "CarManager/statistical";
	}
	
	/**
	 * 获取供货商列表
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getSupportList",method={RequestMethod.GET,RequestMethod.POST}, 
            produces={"application/json;charset=UTF-8"})
	public String getSupportList(){
		List<Support> supportlist = supportManager.selectByExample(null);
		String retjson = JSONArray.toJSONString(supportlist);
		return retjson;
	}

	/**
	 * 删除指定id的车型信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/DeleteCar",method={RequestMethod.GET,RequestMethod.POST})
	public String DeleteCar(HttpServletRequest request){
		String carid = request.getParameter("carid");
		Integer ret = carManager.deleteByPrimaryKey(Integer.parseInt(carid));
		if(ret>0){
			return "forward:/carManager/CarList";
		}
		return "forward:/carManager/CarList";
	}
	
	/**
	 * 获取指定id的车型信息
	 * 并跳转到信息显示页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getCarByView",method={RequestMethod.GET,RequestMethod.POST})
	public String getCarByView(HttpServletRequest request){
		String carid = request.getParameter("carid");
		Car car = carManager.selectByPrimaryKey(Integer.parseInt(carid));
		request.setAttribute("car", car);
		return "CarManager/viewcar";
	}
	
	/**
	 * 获取指定id的车型信息
	 * 并跳转到信息编辑页面
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/getCarByUpdate",method={RequestMethod.GET,RequestMethod.POST})
	public String getCarByUpdate(@ModelAttribute("car") Car car,HttpServletRequest request){
		String carid = request.getParameter("carid");
		car = carManager.selectByPrimaryKey(Integer.parseInt(carid));
		List<Support> sList = supportManager.selectByExample(null);
		request.setAttribute("carbyid", car);
		request.setAttribute("supportList", sList);
		return "CarManager/modifycar";
	}
	@RequestMapping(value="/SaveCarByUpdate",method={RequestMethod.GET,RequestMethod.POST})
	public String SaveCarByUpdate(Car car){
		Integer ret = carManager.updateByPrimaryKeySelective(car);
		if(ret>0){
			return "forward:/carManager/CarList";
		}
		return "forward:/carManager/getCarByUpdate";
	}
	/**
	 * 跳转到汽车信息添加编辑页面
	 * @return
	 */
	@RequestMapping(value="/AddCar",method={RequestMethod.GET,RequestMethod.POST})
	public String AddCar(){
		return "CarManager/addcar";
	}
	/**
	 * 提交要新加的车型信息
	 * @param car
	 * @return
	 */
	@RequestMapping(value="/ToAddCarNews",method={RequestMethod.GET,RequestMethod.POST})
	public String ToAddCarNews(@Valid Car car,BindingResult bindingResult,HttpServletRequest request,HttpServletResponse response,
			@RequestParam(value ="attachs", required = false) MultipartFile[] attachs){
		
		System.out.println("add()================");
		if(bindingResult.hasErrors()){
			return "forward:/carManager/AddCar";
		}
		
		String idPicPath = null;
		String workPicPath = null;
		String errorInfo = null;
		boolean flag = true;
		String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles"); 
		//logger.info("uploadFile path ============== > "+path);
		for(int i = 0;i < attachs.length ;i++){
			MultipartFile attach = attachs[i];
			if(!attach.isEmpty()){
				if(i == 0){
					errorInfo = "uploadFileError";
				}else if(i == 1){
					errorInfo = "uploadWpError";
	        	}
				String oldFileName = attach.getOriginalFilename();//原文件名
				//logger.info("uploadFile oldFileName ============== > "+oldFileName);
				String prefix=FilenameUtils.getExtension(oldFileName);//原文件后缀     
		        //logger.debug("uploadFile prefix============> " + prefix);
				int filesize = 500000;
				//logger.debug("uploadFile size============> " + attach.getSize());
		        if(attach.getSize() >  filesize){//上传大小不得超过 500k
	            	request.setAttribute(errorInfo, " * 上传大小不得超过 500k");
	            	flag = false;
	            }else if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") 
	            		|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
	            	String fileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal.jpg";  
	                //logger.debug("new fileName======== " + attach.getName());
	                File targetFile = new File(path, fileName);  
	                if(!targetFile.exists()){  
	                    targetFile.mkdirs();  
	                }  
	                //保存  
	                try {  
	                	attach.transferTo(targetFile);  
	                } catch (Exception e) {  
	                    e.printStackTrace();  
	                    request.setAttribute(errorInfo, " * 上传失败！");
	                    flag = false;
	                }  
	                if(i == 0){
	                	 idPicPath = path+File.separator+fileName;
	                }else if(i == 1){
	                	 workPicPath = path+File.separator+fileName;
	                }
	                //logger.debug("idPicPath: " + idPicPath);
	                //logger.debug("workPicPath: " + workPicPath);
	                
	            }else{
	            	request.setAttribute(errorInfo, " * 上传图片格式不正确");
	            	flag = false;
	            }
			}
		}
		if(flag){
			if(carManager.insert(car)>0){
				PrintWriter out = null;
				try {
					out = response.getWriter();
			        out.print("<script>window.parent.location.href='CarList';</script>");  
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}  
		        out.flush();
				
			}
		}
		return "forward:/carManager/AddCar";
	}
	
	/**
	 * (没有搜索条件)跳转到汽车信息显示列表
	 * @return
	 */
	@RequestMapping(value="/CarList",method={RequestMethod.GET,RequestMethod.POST})
	public String CarList(HttpSession session){
		session.removeAttribute("seach");
		return "CarManager/showcarlist";
	}
	
	/**
	 * (有搜索条件)跳转到汽车信息显示列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/CarListBySeach",method={RequestMethod.GET,RequestMethod.POST})
	public String CarListBySeach(HttpServletRequest request){
		CarSeach carSeach = new CarSeach();
		carSeach.setCarType(request.getParameter("carType"));
		if(request.getParameter("carSupplier")!=null&&!request.getParameter("carSupplier").equals("")){
			carSeach.setCarSupplier(Integer.parseInt(request.getParameter("carSupplier")));
		}
		carSeach.setPrice(request.getParameter("price"));
		carSeach.setDriveType(request.getParameter("driveType"));
		request.getSession().setAttribute("seach", carSeach);
		System.out.println(carSeach.getCarSupplier());
		return "CarManager/showcarlist";
	}
	
	/**
	 * 通过Ajax动态更新数据
	 * 使用fastjosn将对象转化为json数据返回到视图
	 * @param page
	 * @param rows
	 * @param carSeach
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/ShowCarlist",method={RequestMethod.GET,RequestMethod.POST}, 
            produces={"application/json;charset=UTF-8"})
	public String ShowCarlist(Integer page,Integer rows,HttpServletRequest request){
		CarSeach carSeach = (CarSeach)request.getSession().getAttribute("seach");
		if(carSeach==null){
			carSeach = new CarSeach();
		}
		Map resultMap = new HashMap();
		
		carSeach.setSize(rows);
		carSeach.setStart((page-1)*rows);
		Integer total = carManager.countByCarSeach(carSeach);
		List<CarCustom> list = carManager.selectByExamplewithPage(carSeach);
		List hList = new ArrayList();
		for (CarCustom carCustom : list) {
			Map JSONmap = new HashMap();
			JSONmap.put("id", carCustom.getId());
			JSONmap.put("car_type", carCustom.getType());
			JSONmap.put("inprice", carCustom.getInprice());
			JSONmap.put("outprice", carCustom.getOutprice());
			JSONmap.put("color", carCustom.getColor());
			if("font".equals(carCustom.getEnergy())){
				JSONmap.put("qudong", "前轮驱动");
			}
			if("behand".equals(carCustom.getEnergy())){
				JSONmap.put("qudong", "后轮驱动");
			}
			if("all".equals(carCustom.getEnergy())){
				JSONmap.put("qudong", "四轮驱动");
			}
			JSONmap.put("made", carCustom.getSupport().getName());
			JSONmap.put("jianjie", carCustom.getBrand());
			hList.add(JSONmap);
		}
		resultMap.put("rows", hList);
		resultMap.put("total", ""+total+"");
		
		String retjson = JSONArray.toJSONString(resultMap);
		return retjson;
		
	}
	
}
